<script setup lang="ts">
// 原有脚本逻辑保持不变，仅添加类型注释
import {NSpace, NAvatar, NDropdown, NBreadcrumb, NBreadcrumbItem} from 'naive-ui'
import {computed, ref} from 'vue'
import {generateBreadcrumb} from './MenuUtils'
import {useRouter} from 'vue-router'
import {fetchUserDetails} from "@/api/user/index"
import {fetchRoleDetails} from "@/api/role/index"
import {useAuthStore} from "@/stores/auth_store"

defineOptions({name: 'Header'})

interface Props {
  collapsed: boolean
  menuItems: Menu.MenuModel[]
  activeKey: string | null
}

const props = defineProps<Props>()
const emit = defineEmits(['select'])

const router = useRouter()
const userInfo = ref<User.UserDetails>({
  userId: 0,
  username: '',
  //密码
  password: '',
  email: '',
  name: '',
  createdAt: '',
  updatedAt: '',
  //在线离线
  status: 'ONLINE',
  accountLockedType: 'LOCK',
  //启用,1、开启，2、关闭
  enable: false,
  lastLogin: '',
  //男：MALE 女：FEMALE
  userGender: 'MALE',
  phone: '',
  wechat: '',
  avatar: '',
  defaultRole: 0,
  roles: []
})
const defaultRole = ref<Role.BaseInfo>({
  roleId: 0,
  roleName: '',
  description: '',
  createdAt: '',
  updatedAt: '',
  roleCode: '',
  status: 1,
  home: {
    id: 0,
    title: '',
    name: '',
    icon: '',
    requiresAuth: false,
    disabled: false,
    show: false,
    menuType: 1,
    iconType: 1,
    href: '',
    route: {
      path: '',
      component: ''
    },
  }
})

// 计算属性：生成面包屑导航
const breadcrumbItems = computed(() =>
  generateBreadcrumb(props.menuItems, props.activeKey)
)

// 用户操作菜单配置
const userOptions = [
  {label: '个人信息', key: 'profile'},
  {label: '设置', key: 'settings'},
  {type: 'divider', key: 'divider'},
  {label: '退出登录', key: 'logout'}
]

// 面包屑点击处理
const handleBreadcrumbClick = async (item: Menu.MenuModel) => {
  try {
    if (item.menuType != 1) {
      await router.push({path: item.route ? item.route.path : ''})
      emit('select', item.name)
    }
  } catch (error) {
    console.error('路由跳转失败:', error)
  }
}

// 用户菜单操作处理
const handleUserSelect = (key: string) => {
  switch (key) {
    case 'profile':
      router.push({name: 'profile'})
      break
    case 'settings':
      router.push({name: 'settings'})
      break
    case 'logout':
      useAuthStore().logout()
      router.push({path: "/login"})
      break
  }
}

// 初始化用户数据
const init = async () => {
  const userInfoPromise = await fetchUserDetails()
  userInfo.value = {...userInfoPromise}
  if (userInfoPromise.defaultRole) {
    defaultRole.value = await fetchRoleDetails(userInfoPromise.defaultRole)
  } else {
    defaultRole.value = {}
  }

}

init()
</script>

<template>
  <header class="header-container">
    <!-- 左侧面包屑导航 -->
    <nav class="header-nav">
      <n-breadcrumb separator="›" class="breadcrumb">
        <n-breadcrumb-item
          v-for="item in breadcrumbItems"
          :key="item.name"
          @click="handleBreadcrumbClick(item)"
          class="breadcrumb-item"
        >
          <span class="breadcrumb-text">{{ item.title }}</span>
        </n-breadcrumb-item>
      </n-breadcrumb>
    </nav>

    <!-- 右侧用户信息 -->
    <div class="user-panel">
      <n-space align="center" :size="16">
        <span class="welcome-text">欢迎回来，{{ defaultRole.roleName }}</span>
        <n-dropdown
          :options="userOptions"
          @select="handleUserSelect"
          placement="bottom-end"
          trigger="click"
        >
          <div class="user-info">
            <n-avatar
              round
              size="medium"
              :src="userInfo.avatar"
              class="user-avatar"
              fallback-src="/default-avatar.png"
            />
            <div class="user-meta">
              <span class="username">{{ userInfo.username }}</span>
              <span class="user-role">{{ defaultRole.roleName }}</span>
            </div>
          </div>
        </n-dropdown>
      </n-space>
    </div>
  </header>
</template>

<style scoped>
/* ========== 布局样式 ========== */
.header-container {
  --header-height: 64px;
  --spacing-md: 24px;
  --spacing-sm: 16px;
  --radius-md: 8px;
  --radius-sm: 4px;
  --transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: var(--header-height);
  padding: 0 var(--spacing-md);
  background: #ffffff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  position: relative;
  z-index: 1000;
}

/* ========== 面包屑导航 ========== */
.breadcrumb {
  :deep(.n-breadcrumb-item) {
    font-size: 14px;

    &:not(:last-child) {
      color: rgba(0, 0, 0, 0.6);

      .breadcrumb-text {
        cursor: pointer;
        padding: 6px 8px;
        border-radius: var(--radius-sm);
        transition: var(--transition);

        &:hover {
          background: rgba(0, 0, 0, 0.03);
          color: rgba(0, 0, 0, 0.8);
        }
      }
    }

    &:last-child {
      color: rgba(0, 0, 0, 0.85);
      font-weight: 500;
    }
  }

  :deep(.n-breadcrumb-separator) {
    color: rgba(0, 0, 0, 0.3);
    margin: 0 4px;
  }
}

/* ========== 用户信息面板 ========== */
.user-panel {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px;
  border-radius: var(--radius-md);
  transition: var(--transition);
  cursor: pointer;

  &:hover {
    background: rgba(0, 0, 0, 0.03);
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  }
}

.user-meta {
  display: flex;
  flex-direction: column;
  line-height: 1.4;

  .username {
    font-size: 14px;
    color: rgba(0, 0, 0, 0.85);
    font-weight: 500;
  }

  .user-role {
    font-size: 12px;
    color: rgba(0, 0, 0, 0.45);
  }
}

.welcome-text {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.6);
  padding-right: 12px;
  border-right: 1px solid rgba(0, 0, 0, 0.08);
}

/* ========== 响应式设计 ========== */
@media (max-width: 768px) {
  .header-container {
    padding: 0 16px;
    --header-height: 56px;
  }

  .welcome-text {
    display: none;
  }

  .user-meta {
    display: none;
  }

  .user-info {
    padding: 4px;
  }
}
</style>
